package m4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {

        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        // 创建随机队列，创建交换机
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true,null);
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

        System.out.println("输入绑定键，用空格隔开： ");
        String s = new Scanner(System.in).nextLine(); // aa bb cc
        String[] a = s.split("\\s+");// \s+ 正则表达式，表示1个到多个空白字符

        // 循环遍历输入的绑定键，进行绑定
        for (String k : a) {
            c.queueBind(queue, "direct_logs", k);
        }


        // 正常从队列接受对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String s1 = new String(delivery.getBody());
                // 获取消息时，携带的路由键
                String key = delivery.getEnvelope().getRoutingKey();
                System.out.println(key + " - 收到： " + s1);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };

        c.basicConsume(queue, true,deliverCallback,cancelCallback);

    }


}
